/**
 * 统一日志管理工具
 * 在开发环境显示日志，生产环境可选择性禁用
 */

type LogLevel = 'debug' | 'info' | 'warn' | 'error'

interface LoggerConfig {
  enableInProduction: boolean
  enabledLevels: LogLevel[]
  prefix?: string
}

class Logger {
  private config: LoggerConfig
  private isDevelopment: boolean

  constructor(config: Partial<LoggerConfig> = {}) {
    this.isDevelopment = import.meta.env.DEV
    this.config = {
      enableInProduction: false,
      enabledLevels: ['debug', 'info', 'warn', 'error'],
      prefix: '[App]',
      ...config,
    }
  }

  private shouldLog(level: LogLevel): boolean {
    if (this.isDevelopment) {
      return this.config.enabledLevels.includes(level)
    }
    return this.config.enableInProduction && this.config.enabledLevels.includes(level)
  }

  private formatMessage(
    level: LogLevel,
    message: string,
    ...args: unknown[]
  ): [string, ...unknown[]] {
    const timestamp = new Date().toLocaleTimeString()
    const prefix = this.config.prefix
    const formattedMessage = `${prefix} [${level.toUpperCase()}] ${timestamp} ${message}`
    return [formattedMessage, ...args]
  }

  debug(message: string, ...args: unknown[]): void {
    if (this.shouldLog('debug')) {
      window.console.debug(...this.formatMessage('debug', message, ...args))
    }
  }

  info(message: string, ...args: unknown[]): void {
    if (this.shouldLog('info')) {
      window.console.info(...this.formatMessage('info', message, ...args))
    }
  }

  warn(message: string, ...args: unknown[]): void {
    if (this.shouldLog('warn')) {
      window.console.warn(...this.formatMessage('warn', message, ...args))
    }
  }

  error(message: string, ...args: unknown[]): void {
    if (this.shouldLog('error')) {
      window.console.error(...this.formatMessage('error', message, ...args))
    }
  }

  // API请求日志
  apiRequest(method: string, url: string, data?: unknown): void {
    this.debug(`API请求: ${method.toUpperCase()} ${url}`, data)
  }

  apiResponse(method: string, url: string, status: number, duration: number, data?: unknown): void {
    this.debug(`API响应: ${status} ${method.toUpperCase()} ${url} (${duration}ms)`, data)
  }

  apiError(method: string, url: string, error: unknown, duration?: number): void {
    const durationText = duration != null ? ` (${duration}ms)` : ''
    this.error(`API错误: ${method.toUpperCase()} ${url}${durationText}`, error)
  }
}

// 创建默认logger实例
export const logger = new Logger()

// 创建特定模块的logger
export const createLogger = (prefix: string, config?: Partial<LoggerConfig>) => {
  return new Logger({ ...config, prefix: `[${prefix}]` })
}

// 兼容旧的console调用（逐步迁移用）
export const console = {
  log: (...args: unknown[]) => logger.info(String(args[0] ?? ''), ...args.slice(1)),
  info: (...args: unknown[]) => logger.info(String(args[0] ?? ''), ...args.slice(1)),
  warn: (...args: unknown[]) => logger.warn(String(args[0] ?? ''), ...args.slice(1)),
  error: (...args: unknown[]) => logger.error(String(args[0] ?? ''), ...args.slice(1)),
  debug: (...args: unknown[]) => logger.debug(String(args[0] ?? ''), ...args.slice(1)),
}

export default logger
